package algorithm;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Set;

public class MyLRUCache {
    private LinkedHashMap<Integer, Integer> cache;
    private int capacity;
    public MyLRUCache(int capacity) {
        cache = new LinkedHashMap<>(capacity);
        this.capacity = capacity;
    }

    // get
    public int get(int key) {
        if(!cache.containsKey(key))
            return -1;
        int res = cache.get(key);
        cache.remove(key);
        cache.put(key, res);
        return res;
    }

    // put
    public void put(int key, int value) {
        cache.remove(key);

        if(capacity == cache.size()) {
            Set<Integer> keySet = cache.keySet();
            Iterator<Integer> iterator = keySet.iterator();
            cache.remove(iterator.next());
        }
        cache.put(key, value);
    }
}
